//Master View Component Constructor
function MasterView() {
	var DbHelper = require('ui/common/DbHelper');
	var dbHelper = new DbHelper();
	
	dbHelper.checkVersion();
	
	//create object instance, parasitic subclass of Observable
	var self = Ti.UI.createView({
		backgroundColor : 'white'
	});

	//search bar
	var search = Titanium.UI.createSearchBar({
		showCancel : false,
		hintText: 'Search in English',
		left: 0
	});

	var lang = "mal";

	var dbResult = dbHelper.getRows("mal");
	var tableData = dbResult.data;
	var index = dbResult.index;
	
	var table = Ti.UI.createTableView({
		backgroundColor:'#D3D3D3',
		data: tableData,
		search : search,
		searchHidden : true,
		filterAttribute : 'filter',
		index: index,
  		separatorStyle: Titanium.UI.iPhone.TableViewStyle.GROUPED,
  		bottom: 44
	});
	self.add(table);
	
	self.setFirst = function() {
		var d = tableData[0];
		d.title_en = d.filter;
		self.fireEvent("init", {data: d});	
	};

	//add behavior
	table.addEventListener('click', function(e) {
		if(!e.rowData.ml) {
			return;
		}
		self.fireEvent('itemSelected', {
			ml: e.rowData.ml,
			en: e.rowData.en,
			title_ml : e.rowData.title_ml,
			title_en: e.rowData.filter
		});
	});
	
	self.addEventListener('langClicked', function(e) {
		if(lang == "mal") {
			dbResult = dbHelper.getRows("eng");
			tableData = dbResult.data;
			index = dbResult.index;
		}
		else {
			dbResult = dbHelper.getRows("mal");
			tableData = dbResult.data;
			index = dbResult.index;
		}
		
		table.setData([]);
		table.setIndex(index);
		table.setData(tableData);
		
		if(e.langButton.title == "ENG") {
			e.langButton.title = "MAL";
			lang = "eng";
		}
		else {
			e.langButton.title = "ENG";
			lang = "mal";
		}
	});
	
	var searchButton = Titanium.UI.createButton({
	    image: 'search.png'
	});
	
	var bookmark = Titanium.UI.createButton({
	    systemButton:Titanium.UI.iPhone.SystemButton.BOOKMARKS
	});

	var flexSpace = Titanium.UI.createButton({
	    systemButton:Titanium.UI.iPhone.SystemButton.FLEXIBLE_SPACE
	});

	var toolbar = Titanium.UI.iOS.createToolbar({
	    items:[searchButton, flexSpace, bookmark],
	    bottom:0,
	    borderTop:true,
	    borderBottom:false,
	    barColor: '#000',
	    opacity: 0.9
	});
	
	self.add(toolbar);
	
	searchButton.addEventListener('click', function(e) {
		search.focus();
	});
	
	bookmark.addEventListener('click', function(e) {
		self.fireEvent("showBookmarks", {});
	});
	
	return self;
};

module.exports = MasterView; 